<?php

namespace app\test\controller;

use app\common\lib\Util;
use app\common\model\Orders;
use app\common\model\Recode;
use think\Controller;
use app\common\model\Recode as RecodeModel;
use think\Db;

class TestFortune extends Controller
{
    /**
     * 查询已解锁年运中，连续2年、连续3年某某之日
     */
    private function getDataChanges()
    {
        $type = 3;// 1、幸运之城 2、月运 3、年运
        $version = 2;//这个版本新增学业曲线

        $dir = 'test';
        $filename = 'year_fortune.json';
        $filepath = RUNTIME_PATH . $dir . '/' . $filename;
        $datas = [];
        is_file($filepath) && $datas = json_decode(file_get_contents($filepath), true);

        if (empty($datas))
        {
            $datas = Db::query("select rid, year, topic
from wechat_backup_07_18_14_43_00.app_year_fortune
where rid in (select lv.rid
              from wechat_backup_07_18_14_43_00.app_year_fortune yf
                       left join app_logic_version lv on yf.year = lv.time and yf.rid = lv.rid
              where lv.type = {$type}
                and lv.version = {$version}
              group by yf.rid
              having count(yf.year) > 1)
order by rid,year");
            // 将数据库查询的数据生成到文件中
            Util::createFile($filename, json_encode($datas), $dir);
        }

        echo "年运解锁一年以上的抽样总数：" . count($datas) . '<br>' . PHP_EOL;

        $data = [];

        foreach ($datas as $d0)
        {
            $data[$d0['rid']][$d0['year']] = $d0['topic'];
        }
        echo "抽样档案总数：" . count($data) . '<br>' . PHP_EOL;


//        print_r($data);

        $res2 = [];
        $res3 = [];
        foreach ($data as $rid => $years)
        {
            // 当前档案是否连续
            $num = 0;
            $t = null;
            foreach ($years as $topic)
            {
                // 初始化连续的主题为当前年份的主题、连续年数为1
                if ($t === null || $t !== $topic)
                {
                    $num = 1;
                    $t = $topic;
                }// 连续年数+1
                else
                {
                    $num++;
                }
            }
            // 连续2年及以上
            if ($num > 1)
            {
                $res2[] = $rid;
            }
            // 连续3年及以上
            if ($num > 2)
            {
                $res3[] = $rid;
            }
        }
        echo '有连续2年及以上相同某某之年的数量：' . count($res2) . '<br>' . PHP_EOL;
        echo '有连续3年及以上相同某某之年的数量：' . count($res3) . '<br>' . PHP_EOL;

//        echo "<pre>";
//        print_r($data);
//        echo "</pre>";

//        echo "<pre>";
//        print_r($res2);
//        echo "</pre>";
        exit;
    }

    /**
     * 将档案购买的年运订单重新加入队列,并将订单状态改为1=>待计算
     * @param array $data
     * @return bool|\think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    private function fortune_redis_job($data = [])
    {
        $rid = (string)$data['rid'];
        $uid = $data['uid'];

        $recode_info = [];

        $recodeModel = new RecodeModel();
        // 查询未更改前的档案
        $recode_info [] = $recodeModel->getRecode(['id' => $rid, 'uid' => $uid]);

        //获取当前档案解锁的
        $ordersModel = new Orders();
//        $map =['f.rids'=>['like', "%".$rid."%"],'o.status'=>['in',[1,4]],'o.gid'=>['in',config('goods.month_year_id')]];
        $map = ['o.status' => ['in', [1, 4]], 'o.gid' => ['in', config('goods.month_year_id')]];
        $where1 = "find_in_set($rid,f.rids)";
        try
        {
            $orders = $ordersModel->alias('o')
                ->field('f.time,f.type ftype,f.rids,g.expire_time,o.id oid,o.order_id,o.status ostatus')
                ->join('wechat_backup_07_18_14_43_00.app_goods g', 'o.gid=g.id', 'INNER')
                ->join('wechat_backup_07_18_14_43_00.app_fortune f', 'o.fid=f.id', 'INNER')
                ->where($map)
                ->where($where1)
                ->selectOrFail();
            $orders = json_decode(json_encode($orders, true), true);
        }
        catch (\Exception $e)
        {
            $orders = [];
        }

        if ($orders || !empty($orders))
        {
            $oid = [];
            $order_id = [];
            foreach ($orders as $v)
            {
                $oid[] = $v['oid'];
                $order_id[] = $v['order_id'];
                switch ($v['ftype'])
                {
                    case 2:
                        $start_time = date('Y-m', $v['time']);
                        $end_time = date('Y-m', strtotime($v['expire_time'], $v['time']) - 86400);
                        break;
                    case 3:
                        $start_time = date('Y', $v['time']);
                        $end_time = date('Y', strtotime($v['expire_time'], $v['time']) - 86400);
                        break;
                    default:
                        $start_time = "";
                        $end_time = "";
                }
                $unlock_time = prDates(['start' => $start_time, 'end' => $end_time, 'type' => $v['ftype']]);

                //将运势加入队列运算
                fortune_redis_job(['oid' => $v['oid'], 'order_id' => $v['order_id'], 'recode_info' => $recode_info, 'unlock_time' => $unlock_time, 'ostatus' => 1, 'ftype' => $v['ftype']]);
            }

            try
            {
                //将订单状态修改为1
                $ordersModel->save([
                    'status' => 1,
                ], ['id' => ['in', $oid]]);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), '即将进行重新计算,请稍等');
            }

            //删除订单缓存
            foreach ($orders as $value)
            {
                // 删除订单缓存
                (new Orders())->rm_cache(['oid' => $value['id'], 'del_add' => 0, 'order_id' => $value['order_id'], 'uid' => $uid]);
            }
        }

        return true;
    }

    /**
     * 编辑档案
     * 名人星案审核通过无法编辑
     * @return \think\response\Json|void
     * @throws \app\common\lib\exception\ApiException
     * @throws \Exception
     */
    private function edit()
    {


        $data = json_decode('{"id":553433,"uid":10254602,"name":"\u674e\u67cf\u69601","type":1,"year":1989,"month":10,"day":24,"hour":0,"minute":22,"timezone":8,"birth_country":"\u5317\u4eac\u5e02","birth_province":"\u5317\u4eac\u5e02","birth_city":"\u4e1c\u57ce\u533a","live_country":"\u5317\u4eac\u5e02","live_province":"\u5317\u4eac\u5e02","live_city":"\u4e1c\u57ce\u533a","comments":"\u81ea\u5df1","isself":1,"long_deg":116,"long_min":25,"ew":1,"lat_deg":39,"lat_min":39,"ns":1,"avatar":"\/uploads\/20180903\/10e6022d602a9bc1dbfeb18ca1df7fdf.png","status":1,"from":"zhunle"}', true);

        $this->fortune_redis_job(['rid' => $data['id'], 'uid' => $data['uid']]);
        return;

//        $data = [
//            'id' => input('id/d'),// 档案id
//            'uid' => $this->user['id'],// 用户id
//            'name' => input('name/s', '', 'htmlspecialchars'),// 档案名称
//            'type' => input('type/d'),// 档案类型  1男 | 2 女 | 3 男同 | 4 女同 | 5 事件 | 6 卜卦
//            'year' => input('year/d'),// 出生时间-年
//            'month' => input('month/d'),// 出生时间-月
//            'day' => input('day/d'),// 出生时间-日
//            'hour' => input('hour/d'),// 出生时间-时
//            'minute' => input('minute/d'),// 出生时间-分
//            'timezone' => input('timezone/d'),// 出生时间-时区
//            'birth_country' => input('birth_country/s', '', 'htmlspecialchars'),// 出生地点-省
//            'birth_province' => input('birth_province/s', '', 'htmlspecialchars'),// 出生地点-市
//            'birth_city' => input('birth_city/s', '', 'htmlspecialchars'),// 出生地点-区
//            'live_country' => input('live_country/s', '', 'htmlspecialchars'),// 现居地-省
//            'live_province' => input('live_province/s', '', 'htmlspecialchars'),// 现居地-省
//            'live_city' => input('live_city/s', '', 'htmlspecialchars'),// 现居地-省
//            'comments' => input('comments/s', '', 'htmlspecialchars'),// 档案标签如 自己 朋友 案例
//            'isself' => input('isself/d'),// 档案是否为自己 0 否 | 1 是（自己的档案无法删除，无法更改为其他标签）
//            'long_deg' => input('long_deg/d'),// 经度-度
//            'long_min' => input('long_min/d'),// 经度-分
//            'ew' => input('ew/d'),// 东经|西经 1|-1
//            'lat_deg' => input('lat_deg/d'),// 纬度-度
//            'lat_min' => input('lat_deg/d'),// 纬度-度
//            'ns' => input('ns/d'),// 南纬北纬  1|-1
//            'avatar' => input('avatar/s', '', 'htmlspecialchars'),// 头像地址
//            'status' => 1,// 档案状态
//            'from' => 'zhunle',// 档案来源
////            'is_summer' => input('is_summer/d'),// 是否开启夏令时
////            'is_summer' => isSummerTime($hour, $minute, 0, $month, $day, $year) ? 1 : 0,// 是否开启夏令时
//        ];
        $data['is_summer'] = isSummerTime($data['hour'], $data['minute'], 0, $data['month'], $data['day'], $data['year']) ? 1 : 0;// 是否开启夏令时

        $validate = validate('Recode');

        if (!$validate->scene('edit')->check($data)) return show(config('code.error'), (string)$validate->getError());

        $recodeModel = new RecodeModel();
        // 查询未更改前的档案
        $recode_old = $recodeModel->getRecode(['id' => $data['id'], 'uid' => $data['uid']]);

        if ($recode_old['isself'] != 1 && $data['isself'] == 1) return show(config('code.error'), '不能添加多个自己的档案');

        // 检测档案编辑是否更改时间
        $timeChange = false;// 默认表示时间未进行更新
        $old_time = strtotime($recode_old['year'] . '-' . $recode_old['month'] . '-' . $recode_old['day'] . ' ' . $recode_old['hour'] . ':' . $recode_old['minute']);
        $new_time = strtotime($data['year'] . '-' . $data['month'] . '-' . $data['day'] . ' ' . $data['hour'] . ':' . $data['minute']);
        // 时间有变动
        if ($old_time != $new_time || $recode_old['timezone'] != $data['timezone'] || $recode_old['is_summer'] != $data['is_summer'])
        {
            $timeChange = true;

            if (in_array($data['id'], config('vip'))) $rec = false;
            // 检测是否存在档案相关已付款订单
            else $rec = \app\common\cachemodel\Recode::checkAboutOrders(['uid' => $data['uid'], 'id' => $data['id']]);

            // 若有，则档案时间只能为当天内变动，若跨日期，则只能在两小时以内变动
            if ($rec === true)
            {
                // 判断or_day是否存在
                if (empty($recode_old['or_day']) || !$recode_old['or_day'])
                {
                    $recode_old['or_day'] = $recode_old['day'];
                    $data['or_day'] = $recode_old['day'];
                }

                $limit_time = strtotime($recode_old['year'] . '-' . $recode_old['month'] . '-' . $recode_old['or_day'] . ' 12:00');
                $max = $limit_time + 3600 * 14;
                $min = $limit_time - 3600 * 14;

                if ($new_time > $max || $new_time < $min) return show(config('code.error'), '由于该档案购买过付费项目，修改功能受限，改后时间不能与原档案时间差超过两个小时');
            }
        }
        // 检测档案编辑是否更改出生地经纬度
        $old_longitude = ($recode_old['long_deg'] + $recode_old['long_min'] / 60) * $recode_old['ew'];
        $old_latitude = ($recode_old['lat_deg'] + $recode_old['lat_min'] / 60) * $recode_old['ns'];
        $new_longitude = ($data['long_deg'] + $data['long_min'] / 60) * $data['ew'];
        $new_latitude = ($data['lat_deg'] + $data['lat_min'] / 60) * $data['ns'];

        $longLatChange = false;

        if ($old_longitude != $new_longitude || $old_latitude != $new_latitude) $longLatChange = true;

//        $Astro = new AstroIndex();
        // 获取当前数据星盘日月水金火木土等星落座落宫
//        $astro_data = $Astro->getTheRecodeAstro($data['year'], $data['month'], $data['day'], $data['hour'], $data['minute'], $new_longitude, $new_latitude, $data['timezone']);

//        try
//        {
//            // 更新档案数据
//            $recodeModel->update($data);
//            // 如果更新的是自己的档案 且 用户修改了档案名称或头像 则更新用户数据 昵称 头像
//            if ($recode_old['isself'] == 1
//                && ($data['name'] != $recode_old['name'] || $data['avatar'] != $recode_old['avatar']))
//            {
//                (new User())->updateUserinfo(['id' => $data['uid']], ['nickname' => $data['name'], 'avatar' => $data['avatar']]);
//            }
//            // 更新档案行星数据
//            if ($timeChange || $longLatChange)
//            {
//                Db::table('app_recode_astro')->where(['id' => $recode_old['aid']])->update($astro_data);
//            }
//            $data['aid'] = $recode_old['aid'];
//
//            // 档案更新时更新用户档案缓存
//            Cache::set('recode_' . $data['id'], $data);
//            // 档案更新时更新用户档案日月升缓存
//            Cache::rm('recode_astro_' . $data['id']);
//
//            // 删除命运之城数据库里存储的数据  和 缓存的命运之城数据
//            $map_lines = (new Map())->getRecodeUnlockLines(['uid' => $data['uid'], 'rid' => $data['id'], 'isself' => $data['isself']]);
//
//            if ($map_lines[11] == 1) (new FateCity())->removeFateCity(['uid' => $data['uid'], 'rid' => $data['id']]);
//
//        }
//        catch (\Exception $e)
//        {
//            \think\Log::write('编辑档案失败：' . $e->getMessage(), 'edit_recode_error', true);
//            return show(config('code.error'), '更新失败');
//        }

        //将档案购买的年运订单重新加入队列
        $this->fortune_redis_job(['rid' => $data['id'], 'uid' => $data['uid']]);

//        return show(config('code.success'), '更新成功', array_merge($data, $astro_data));

    }

}
